package com.andatsoft.laisim.dialog;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.activity.BaseActivity;
import com.andatsoft.laisim.activity.LibraryActivity;
import com.andatsoft.laisim.adapter.LibraryTwoLineListAdapter;
import com.andatsoft.laisim.db.DataBaseAccess;
import com.andatsoft.laisim.entity.Playlist;
import com.andatsoft.laisim.entity.Song;
import com.andatsoft.laisim.entity.TwoLineItem;
import com.andatsoft.laisim.utils.Common;
import com.andatsoft.laisim.utils.ToastMessage;

public class CreatePlaylistFromToolBoxDialog extends BaseActivity {

	private ListView mListView;
	private EditText mEtPlaylistName;
	private TextView mTvOk;
	private List<TwoLineItem> mListItem;
	private List<Song> mListSong;
	private LibraryTwoLineListAdapter mAdapter;
	private int mSelectdPlaylistId = -1;
	private RadioGroup mRadioGroup;
	private int mCreateMode = 0;// 0: Create New, 1: Append to

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		getWindow()
				.setBackgroundDrawable(
						new ColorDrawable(getSelectedTheme()
								.getDialogBackgroundColor()));
		setContentView(R.layout.dialog_create_playlist_from_toolbox);
		int cmd = getIntent().getIntExtra(
				Common.INTENT_DATA_CREATE_PLAYLIST_FROM_TOOLBOX_CMD, -1);
		if (cmd == -1)
			return;
		mListItem = new ArrayList<TwoLineItem>();
		mListSong = new ArrayList<Song>();
		initViews();
		setupListeners();
		fillData();
		getSongListSrc(cmd);
	}

	private void initViews() {
		mListView = (ListView) findViewById(R.id.list_dialog_create_playlist_from_toolbox);
		mEtPlaylistName = (EditText) findViewById(R.id.et_dialog_create_playlist_from_toolbox_name);
		mEtPlaylistName.setBackgroundColor(getSelectedTheme()
				.getDialogTextColor());
		mEtPlaylistName.setTextColor(getSelectedTheme()
				.getDialogBackgroundColor() | 0xff000000);
		mTvOk = (TextView) findViewById(R.id.tv_create_playlist_from_toolbox_dialog_ok);
		mRadioGroup = (RadioGroup) findViewById(R.id.radio_group_dialog_create_playlist_from_toolbox_mode);
		((RadioButton) mRadioGroup.getChildAt(0))
				.setTextColor(getSelectedTheme().getDialogTextColor());
		((RadioButton) mRadioGroup.getChildAt(1))
		.setTextColor(getSelectedTheme().getDialogTextColor());
		mTvOk.setTextColor(getSelectedTheme().getDialogTextColor());
		((TextView) findViewById(R.id.tv_title_dialog_create_playlist_from_toolbox_name))
				.setTextColor(getSelectedTheme().getDialogTextColor());
//		((TextView) findViewById(R.id.tv_static_dialog_create_playlist_from_toolbox_name))
//				.setTextColor(getSelectedTheme().getDialogTextColor());
	}

	private void setupListeners() {
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int pos,
					long arg3) {
				mAdapter.setSelectedItem(pos);
				mAdapter.notifyDataSetChanged();
				mSelectdPlaylistId = mListItem.get(pos).id;
			}
		});

		mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				Log.d("radfoi", checkedId + "");
				switch (checkedId) {
				case R.id.radio_btn_dialog_create_playlist_from_toolbox_create_new:
					mListView.setVisibility(View.GONE);
					mCreateMode = 0;
					mEtPlaylistName.setEnabled(true);
					break;
				case R.id.radio_btn_dialog_create_playlist_from_toolbox_append_to:
					mListView.setVisibility(View.VISIBLE);
					mCreateMode = 1;
					mEtPlaylistName.setEnabled(false);
					break;
				default:
					break;
				}
			}
		});

		mTvOk.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					return true;

				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					if (mCreateMode == 0) {
						// create new
						String playlistName = mEtPlaylistName.getText()
								.toString();
						if (playlistName == null || playlistName.equals("")) {
							playlistName = getString(R.string.common_text_playlist_default);
						}
						DataBaseAccess db = DataBaseAccess.getInstance(getApplicationContext());
						Playlist pl = new Playlist(playlistName, mListSong);
						if (db.addPlaylist(pl)) {
							new ToastMessage(getApplicationContext())
									.showLongMessage(getString(R.string.create_playlist_add_ok));
						} else {
							new ToastMessage(getApplicationContext())
									.showLongMessage(getString(R.string.create_playlist_add_failed));
						}
					} else {
						// append to
						String playlistName = mEtPlaylistName.getText()
								.toString();
						if (playlistName == null || playlistName.equals("")) {
							playlistName = getString(R.string.common_text_playlist_default);
						}
						DataBaseAccess db = DataBaseAccess.getInstance(getApplicationContext());
						if (mSelectdPlaylistId < 0) {
							// just like add new playlist
							Playlist pl = new Playlist(playlistName, mListSong);
							if (db.addPlaylist(pl)) {
								new ToastMessage(getApplicationContext())
										.showLongMessage(getString(R.string.create_playlist_add_ok));
							} else {
								new ToastMessage(getApplicationContext())
										.showLongMessage(getString(R.string.create_playlist_add_failed));
							}
						} else {
							db.addSongToPlaylist(mSelectdPlaylistId, mListSong);
							new ToastMessage(getApplicationContext())
									.showLongMessage(getString(R.string.create_playlist_from_toolbox_dialog_append_to_ok));
						}
					}
					Intent i = new Intent();
					i.putExtra(Common.RESULT_DATA_CREATE_PLAYLIST_ID,
							mSelectdPlaylistId);
					setResult(Common.RESULT_CODE_CREATE_PLAYLIST, i);
					finish();
					return true;
				}

				return false;
			}
		});
	}

	private void fillData() {
		DataBaseAccess db = DataBaseAccess.getInstance(getApplicationContext());
		mListItem = db.getAllPlayList();
		mAdapter = new LibraryTwoLineListAdapter(getApplicationContext(),
				mListItem);
		mListView.setAdapter(mAdapter);
	}

	private void getSongListSrc(int cmd) {
		DataBaseAccess db = DataBaseAccess.getInstance(getApplicationContext());
		switch (cmd) {
		case LibraryActivity.TYPE_SONG:
			int songId = getIntent().getExtras().getInt(
					Common.INTENT_DATA_CREATE_PLAYLIST_FROM_TOOLBOX_SONGID);
			Song s = db.getSong(songId);
			if (s == null)
				break;
			mListSong.add(s);
			break;
		case LibraryActivity.TYPE_ALBUM:
			String albumStr = getIntent().getExtras().getString(
					Common.INTENT_DATA_CREATE_PLAYLIST_FROM_TOOLBOX_ALBUM);
			String[] data = albumStr.split("6_99_6");
			if (data == null || data.length != 2)
				break;
			mListSong.addAll(db.getSongsFromAlbum(data[0], data[1]));
			break;
		case LibraryActivity.TYPE_ARTIST:
			String artistStr = getIntent().getExtras().getString(
					Common.INTENT_DATA_CREATE_PLAYLIST_FROM_TOOLBOX_ARTIST);
			mListSong.addAll(db.getSongByArtist(artistStr));
			break;
		case LibraryActivity.TYPE_GENRE:
			String genreStr = getIntent().getExtras().getString(
					Common.INTENT_DATA_CREATE_PLAYLIST_FROM_TOOLBOX_GENRE);
			mListSong.addAll(db.getSongByGenre(genreStr));
			break;
		case LibraryActivity.TYPE_FOLDER:
			String folderStr = getIntent().getExtras().getString(
					Common.INTENT_DATA_CREATE_PLAYLIST_FROM_TOOLBOX_FOLDER);
			mListSong.addAll(db.getSongsByFolder(folderStr));
			break;
		}
	}
}
